package com.example.gobang_system.service.manager;

import com.example.gobang_system.common.pojo.Room;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class RoomManager {
    /**
     * key: roomId
     * value: Room 对象
     */
    private ConcurrentHashMap<String, Room> rooms = new ConcurrentHashMap<>();
    /**
     * key: userId
     * value: roomId
     * 方便根据玩家查询对应房间
     */
    private ConcurrentHashMap<Long, String> userIdToRoomId = new ConcurrentHashMap<>();

    /**
     * 创建游戏房间
     * @param room
     * @param userId1
     * @param userId2
     */
    public void add(Room room, Long userId1, Long userId2) {
        rooms.put(room.getRoomId(), room);
        userIdToRoomId.put(userId1, room.getRoomId());
        userIdToRoomId.put(userId2, room.getRoomId());
    }

    /**
     * 删除游戏房间
     * @param roomId
     * @param userId1
     * @param userId2
     */
    public void remove(String roomId, Long userId1, Long userId2) {
        if (null != roomId) {
            rooms.remove(roomId);
        }
        if (null != userId1) {
            userIdToRoomId.remove(userId1);
        }
        if (null != userId2) {
            userIdToRoomId.remove(userId2);
        }
    }

    /**
     * 通过房间号获取游戏房间
     * @param roomId
     * @return
     */
    public Room getRoomByRoomId(String roomId) {
        return rooms.get(roomId);
    }

    /**
     * 通过玩家 id 获取游戏房间
     * @param userId
     * @return
     */
    public Room getRoomByUserId(Long userId) {
        String roomId = userIdToRoomId.get(userId);
        if (null == roomId) {
            return null;
        }
        return rooms.get(roomId);
    }


    @Scheduled(cron = "0 0 5 * * ?") // 每条凌晨 5 点执行一次定时任务
    public void handleEmptyRooms() {
        log.info("执行定时任务");
        // 遍历 rooms
        Iterator<String> iterator = rooms.keySet().iterator();
        while (iterator.hasNext()) {
            String roomId = iterator.next();
            Room room = rooms.get(roomId);
            if (null == room.getUser1() && null == room.getUser2()) {
                Long createTime = Long.parseLong(roomId.substring(32, roomId.length())); // 创建时间
                if (System.currentTimeMillis() - createTime > 60 * 60 * 1000) {
                    log.info("删除空房间: {}", roomId);
                    iterator.remove();
                }
            }
        }
    }
}
